package com.zhongxi.guoyuan.fragment.beautifulStoreOrder;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.beautifulStoreOrder.StoreOrderHasCompleteAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderData;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.beautifulStore.BeautifulCommentActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class StoreOrderHasCompleteFragment extends BaseFragment implements AdapterView.OnItemClickListener, OnRefreshListener2<ListView> {

    private static final int REQUESTSTORECOM = 1;
    private PullToRefreshListView lvList;
    private List<BeautifulStoreOrderData> data = new ArrayList<BeautifulStoreOrderData>();
    private StoreOrderHasCompleteAdapter adapter;
    private BeautifulStoreOrderResult result;
    private String type;

    private Map<String, String> map = new HashMap<>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pos = (int) msg.obj;
            switch (msg.what) {
                case 0://确认操作
                    goSubmit();
                    break;
                case 1:  //投诉
                    showComplaint();
                    break;
            }

        }
    };

    private void goSubmit() {
        BeautifulStoreOrderData beautifulStoreOrderData = data.get(pos);
        Intent intent = new Intent(getContext(), BeautifulCommentActivity.class);
        intent.putExtra("info", beautifulStoreOrderData);
        startActivityForResult(intent, REQUESTSTORECOM);

    }

    private String content;

    /**
     * 去投诉
     */
    private void showComplaint() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_to_complaint, null);
        final EditText editText = (EditText) view.findViewById(R.id.etTips_fuwu);
        final TextView textView = (TextView) view.findViewById(R.id.tvNum_fuwu);
        TextView submit = (TextView) view.findViewById(R.id.tv_submit_complaint);
        ImageView cancel = (ImageView) view.findViewById(R.id.post_nopay_ivCancel);
        builder.setView(view);
        final AlertDialog dialog = builder.create();

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                MyTextUtils.TextChangeUtils(context, textView, editable, 150);
            }
        });


        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                content = editText.getText().toString().trim();

                if (null != content && !"".equals(content)) {
                    getComplaint(content);
                    dialog.dismiss();
                } else {
                    showShortToast("请输入您的意见！");
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    private JSONObject shopInfo;

    private void getComplaint(String content) {
        type = "complaint";
        map.clear();
        map.put("shopid", data.get(pos).getShopid());
        map.put("orderid", data.get(pos).getId());
        map.put("content", content);
        getServer(Url.INNER_COMPLAIN, map, "", false, null, "post");
    }

    private ListView listView;
    private int pos;

    private void getOrderData() {
        type = "order";
        String str = "&page=" + pageNum;
        getServer(Url.STORE_CONFIRMED, null, str, false, null, "get");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_beautyorder_has_no_apply, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        lvList = (PullToRefreshListView) getView().findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);  //支持上拉和下拉加载更多
        adapter = new StoreOrderHasCompleteAdapter(context, data, handler, this);
        lvList.setAdapter(adapter);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
            getOrderData();
    }

    @Override
    protected void initData() {
        super.initData();

        getOrderData();
        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setText("亲,你还没有已操作数据哟!");
        tv.setTextSize(20);
        //当界面为空的时候显示的视图
        lvList.setEmptyView(tv);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnItemClickListener(this);
        lvList.setOnRefreshListener(this);
        listView = lvList.getRefreshableView();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position - 1 == adapter.getmExpandedMenuPos()) {
            adapter.setmExpandedMenuPos(-1);
        } else {
            adapter.setmExpandedMenuPos(position - 1);
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(position);
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("order".equals(type)) {
                result = gson.fromJson(response, BeautifulStoreOrderResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (pageNum == 1) {
                    data.clear();
                }
                JSONObject jsonObject = new JSONObject(response);
                if (null != result.getData() && result.getData().size() > 0) {
                    data.addAll(result.getData());
                    shopInfo = jsonObject.optJSONObject("shopInfo");
                    adapter.setShopInfo(shopInfo);
                }
                adapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            } else if ("complaint".equals(type)) {
                BaseResponse res = gson.fromJson(response, BaseResponse.class);
                if (null != res.getSafeobj() && !"".equals(res.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(res.getSafeobj());
                }
                showShortToast("投诉成功");
                data.get(pos).setStatus("4");
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            if (type.equals("order") || type.equals("complaint")) {
                if (result.getCode() == 1201) {
                    showShortToast("店铺已关闭");
                } else if (result.getCode() == 1666) {
                    showShortToast("服务不可用，服务器异常");
                } else if (result.getCode() == 1690) {
                    showShortToast("服务台信息未设置");
                }
            }

            lvList.onRefreshComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getOrderData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getOrderData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        if (requestCode == REQUESTSTORECOM && resultCode == BeautifulCommentActivity.RESULTCODECOMMEND) {
            if (pos >= 0) {
                data.remove(pos);
                adapter.notifyDataSetChanged();
            }
        }
    }
}
